package com.x.provider.general.factory.dto;

import com.x.core.utils.BeanUtil;
import com.x.provider.api.general.enums.CmsOptions;
import com.x.provider.api.general.model.dto.cms.*;
import com.x.provider.general.model.domain.cms.Content;
import com.x.provider.general.model.domain.cms.ContentMedia;
import com.x.provider.general.model.domain.cms.ContentMediaPicture;
import com.x.provider.general.model.domain.cms.ContentMediaVideo;
import com.x.provider.general.service.cms.ContentService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CmsDTOFactoryImpl implements CmsDTOFactory{

    private ContentService contentService;

    public CmsDTOFactoryImpl(ContentService contentService){
        this.contentService = contentService;
    }

    @Override
    public List<ContentDTO> prepare(List<Content> src, List<String> options) {
        if (CollectionUtils.isEmpty(src)){
            return new ArrayList<>();
        }
        List<ContentDTO> result = BeanUtil.prepare(src, ContentDTO.class);
        if (options.contains(CmsOptions.CONTENT_MEDIA)) {
            prepareContentMedia(result);
        }
        return result;
    }

    private void prepareContentMedia(List<ContentDTO> result) {
        List<Long> contentIdList = result.stream().map(item -> item.getId()).collect(Collectors.toList());
        Map<Long, List<ContentMediaDTO>> contentMediaMap = BeanUtil.prepare(contentService.listContentMedia(contentIdList), ContentMediaDTO.class).stream()
                .collect(Collectors.groupingBy(item -> item.getContentId()));
        Map<Long, ContentMediaVideoDTO> contentMediaVideoMap = BeanUtil.prepare(contentService.listContentMediaVideo(contentIdList), ContentMediaVideoDTO.class).stream()
                .collect(Collectors.toMap(item -> item.getContentMediaId(), item -> item));
        Map<Long, ContentMediaPictureDTO> contentMediaPictureMap = BeanUtil.prepare(contentService.listContentMediaPicture(contentIdList), ContentMediaPictureDTO.class).stream()
                .collect(Collectors.toMap(item -> item.getContentMediaId(), item -> item));
        result.stream().forEach(item -> {
            List<ContentMediaDTO> contentMedias = contentMediaMap.get(item.getId());
            if (CollectionUtils.isEmpty(contentMedias)) {
                return;
            }
            contentMedias.stream().forEach(opt -> {
                opt.setContentMediaVideo(contentMediaVideoMap.get(opt.getId()));
                opt.setContentMediaPicture(contentMediaPictureMap.get(opt.getId()));
            });
            item.setContentMediaList(contentMedias);
        });
    }
}
